import axios from 'axios';
import { ElMessage } from 'element-plus';
// 注意：不再需要导入store，因为401/403错误已由main.js中的全局响应拦截器统一处理

// API 基础路径 (使用相对路径，依赖全局 Axios 配置)
const API_BASE_PATH = '/api/exams';

/**
 * 处理 API 错误
 * @param {Error} error Axios 错误对象
 * @param {string} defaultMessage 默认错误消息
 * @returns {{success: boolean, message: string, data: null}}
 */
const handleApiError = (error, defaultMessage = '操作失败') => {
  console.error('Exam API Error:', error);
  let message = defaultMessage;
  if (error.response) {
    const status = error.response.status;
    // 尝试从后端响应获取错误信息
    message = error.response.data?.message || error.response.data?.error || message;
    if (status === 401) {
      message = '认证失败，请重新登录';
      // 401错误已由全局响应拦截器处理，这里不需要再调用logout
    } else if (status === 403) {
      message = '您没有权限执行此操作，请确认您是该考试的创建者或具有相应权限';
      // 403错误不应该触发logout，只显示权限不足消息
    }
  }
  ElMessage.error(message);
  return { success: false, message, data: null };
};

/**
 * 获取所有考试列表 (管理员/教师)
 * @returns {Promise<object>} {success, data?, message?}
 */
export const getAllExams = async () => {
  try {
    const response = await axios.get(API_BASE_PATH);
    // 包装响应，确保返回 { success: true, data: [...] }
    if (Array.isArray(response.data)) {
       return { success: true, data: response.data };
    } else {
       // 如果后端格式变了，尝试兼容旧格式或记录错误
       console.warn('Unexpected response format from GET /api/exams', response.data);
       // 假设它可能返回 {success, data} 结构
       return response.data?.success ? response.data : { success: false, data: null, message: '响应格式不正确' };
    }
  } catch (error) {
    return handleApiError(error, '获取所有考试列表失败');
  }
};

/**
 * 获取教师创建的考试列表
 * @returns {Promise<object>} {success, data?, message?}
 */
export const getTeacherExams = async () => {
  try {
    const response = await axios.get(`${API_BASE_PATH}/teacher`);
    // 包装响应
    if (Array.isArray(response.data)) {
       return { success: true, data: response.data };
    } else {
       console.warn('Unexpected response format from GET /api/exams/teacher', response.data);
       return response.data?.success ? response.data : { success: false, data: null, message: '响应格式不正确' };
    }
  } catch (error) {
    return handleApiError(error, '获取教师考试列表失败');
  }
};

/**
 * 获取指定班级的学生考试列表
 * @param {number|string} classId 班级 ID (必须提供)
 * @returns {Promise<object>} {success, data?, message?}
 */
export const getStudentExams = async (classId) => {
  if (!classId) {
    const errorMsg = '必须提供班级 ID 才能获取考试列表';
    // ElMessage.error(errorMsg); // 不在这里提示，让调用者处理
    console.warn(errorMsg);
    return { success: false, data: [], message: errorMsg }; // 返回空数组，避免页面出错
  }
  try {
    // 修改 API 调用，添加 classId 查询参数
    const response = await axios.get(`${API_BASE_PATH}/student`, {
        params: { classId } 
    });
    // 包装响应
    if (Array.isArray(response.data)) {
       return { success: true, data: response.data };
    } else {
        console.warn('Unexpected response format from GET /api/exams/student?classId=', classId, response.data);
       return response.data?.success ? response.data : { success: false, data: [], message: '响应格式不正确' }; // 返回空数组
    }
  } catch (error) {
    // 传入 classId 以便错误处理函数可以记录更详细的信息（如果需要）
    return handleApiError(error, `获取班级 ${classId} 考试列表失败`);
  }
};

/**
 * 获取单个考试详情
 * @param {number|string} id 考试ID
 * @returns {Promise<object>} {success, data?, message?}
 */
export const getExamDetail = async (id) => {
  try {
    const response = await axios.get(`${API_BASE_PATH}/${id}`);
    // 包装响应，确保返回 { success: true, data: {exam object} }
    // 检查返回的是否是一个有效的对象（至少有 id）
    if (response.data && typeof response.data === 'object' && response.data.id) {
        return { success: true, data: response.data };
    } else {
        console.warn('Unexpected response format from GET /api/exams/{id}', response.data);
        // 尝试兼容可能返回的 {success, data} 结构，虽然测试表明不是这样
        return response.data?.success ? response.data : { success: false, data: null, message: '响应格式不正确或缺少数据' };
    }
  } catch (error) {
    return handleApiError(error, '获取考试详情失败');
  }
};

/**
 * 创建考试
 * @param {object} examData 考试数据 (根据 API 文档)
 * @returns {Promise<object>} {success, data?, message?}
 */
export const createExam = async (examData) => {
  try {
    // 假设成功时后端返回 {success: true, data: createdExam}
    const response = await axios.post(API_BASE_PATH, examData);
    return response.data; 
  } catch (error) {
    return handleApiError(error, '创建考试失败');
  }
};

/**
 * 更新考试
 * @param {number|string} id 考试ID
 * @param {object} examData 考试数据
 * @returns {Promise<object>} {success, data?, message?}
 */
export const updateExam = async (id, examData) => {
  try {
    // 假设成功时后端返回 {success: true, data: updatedExam}
    const response = await axios.put(`${API_BASE_PATH}/${id}`, examData);
    return response.data;
  } catch (error) {
    return handleApiError(error, '更新考试失败');
  }
};

/**
 * 保存考试草稿 (注意：API 是 POST /{id}/draft，不是 PUT)
 * @param {number|string} id 考试ID
 * @param {object} examData 考试数据
 * @returns {Promise<object>} {success, data?, message?}
 */
export const saveExamDraft = async (id, examData) => {
  try {
    // 假设成功时后端返回 {success: true, message: "..."} 或包含更新后的草稿
    const response = await axios.post(`${API_BASE_PATH}/${id}/draft`, examData);
    return response.data; 
  } catch (error) {
    return handleApiError(error, '保存草稿失败');
  }
};

/**
 * 删除考试
 * @param {number|string} id 考试ID
 * @returns {Promise<object>} {success, message?}
 */
export const deleteExam = async (id) => {
  try {
    const response = await axios.delete(`${API_BASE_PATH}/${id}`);
    return response.data; // 后端返回 {success, message}
  } catch (error) {
    return handleApiError(error, '删除考试失败');
  }
};

/**
 * 发布考试
 * @param {number|string} id 考试ID
 * @returns {Promise<object>} {success, data?, message?}
 */
export const publishExam = async (id) => {
  try {
    const response = await axios.post(`${API_BASE_PATH}/${id}/publish`);
    return response.data; // 后端返回 {success, message, data: {updated exam info}}
  } catch (error) {
    return handleApiError(error, '发布考试失败');
  }
};

/**
 * 开始考试 (教师操作)
 * @param {number|string} id 考试ID
 * @returns {Promise<object>} {success, data?, message?}
 */
export const startTeacherExam = async (id) => {
  try {
    const response = await axios.post(`${API_BASE_PATH}/${id}/start`);
    return response.data; // 后端返回 {success, message, data: {exam info}}
  } catch (error) {
    return handleApiError(error, '开始考试失败');
  }
};

/**
 * 结束考试 (教师操作)
 * @param {number|string} id 考试ID
 * @returns {Promise<object>} {success, data?, message?}
 */
export const endTeacherExam = async (id) => {
  try {
    const response = await axios.post(`${API_BASE_PATH}/${id}/end`);
    return response.data; // 后端返回 {success, message, data: {exam info}}
  } catch (error) {
    return handleApiError(error, '结束考试失败');
  }
};

/**
 * 获取指定考试的所有提交记录 (教师用)
 * @param {number|string} examId 考试ID
 * @returns {Promise<object>} {success, data?, message?} data 是记录数组
 */
export const getExamRecords = async (examId) => {
  try {
    const response = await axios.get(`${API_BASE_PATH}/${examId}/records`);
    // 直接返回后端数据，假设格式为 {success, data: [...]} 或直接是 [...]?
    // 根据文档，似乎应该直接返回数组，包装一下确保一致性
    if (Array.isArray(response.data)) {
        return { success: true, data: response.data };
    } else if (response.data && response.data.success) {
        return response.data; // 兼容后端可能返回 {success: true, data: [...]} 的情况
    } else {
        console.warn(`Unexpected response format from GET /api/exams/${examId}/records`, response.data);
        return { success: false, data: [], message: '获取考试记录响应格式不正确' };
    }
  } catch (error) {
    return handleApiError(error, '获取考试记录失败');
  }
};

/**
 * 开始批改指定的考试记录 (教师用)
 * @param {number|string} recordId 考试记录ID
 * @returns {Promise<object>} {success, data?, message?} data 包含详细批改信息
 */
export const startMarking = async (recordId) => {
  try {
    const response = await axios.post(`${API_BASE_PATH}/records/${recordId}/start-marking`);
    // 后端返回 {success, message, data: {record detail with split questions}}
    return response.data;
  } catch (error) {
    return handleApiError(error, '开始批改失败');
  }
};

/**
 * 提交批改结果 (教师用)
 * @param {number|string} recordId 考试记录ID
 * @param {object} markingData 批改数据 {score, comments, questionScores}
 * @returns {Promise<object>} {success, data?, message?} data 包含更新后的记录信息
 */
export const submitMarking = async (recordId, markingData) => {
  try {
    const response = await axios.post(`${API_BASE_PATH}/records/${recordId}/submit-marking`, markingData);
    // 后端返回 {success, message, data: {updated record}}
    return response.data;
  } catch (error) {
    return handleApiError(error, '提交批改失败');
  }
};

// --- Student Exam Actions ---

/**
 * 学生开始考试
 * @param {number|string} id 考试ID
 * @param {number|string} classId 班级ID (必须提供)
 * @returns {Promise<object>} {success, data?, message?} data 包含 questions, remainingTime 等
 */
export const startStudentExam = async (id, classId) => {
  if (!classId) {
      const errorMsg = '必须提供班级ID才能开始考试';
      ElMessage.error(errorMsg);
      return { success: false, data: null, message: errorMsg };
  }
  try {
    const response = await axios.post(`${API_BASE_PATH}/${id}/start-exam`, null, { 
        params: { classId } 
    });
    // 假设成功响应包含 {success: true, data: { questions: [], remainingTime: ... }}
    if (response.data && response.data.success) {
        return response.data;
    } else {
        const message = response.data?.message || '开始考试失败或响应格式不正确';
        ElMessage.error(message);
        return { success: false, data: null, message };
    }
  } catch (error) {
    return handleApiError(error, '开始考试请求失败');
  }
};

/**
 * 保存单个题目答案
 * @param {number|string} examId 考试ID
 * @param {number|string} questionId 题目ID
 * @param {any} answerData 答案数据 (根据题目类型是字符串、数组等)
 * @returns {Promise<object>} {success, message?}
 */
export const saveAnswer = async (examId, questionId, answerData) => {
    // 注意：请求体是 { answer: ... }
    const payload = { answer: answerData };
    try {
        const response = await axios.post(`${API_BASE_PATH}/${examId}/questions/${questionId}/answer`, payload);
        // 假设成功响应是 {success: true, message: "..."}
        return response.data; 
    } catch (error) {
        // 自动保存失败通常不强烈提示用户，以免干扰答题，可以在控制台记录
        console.error('Auto-save answer failed:', error.response?.data || error.message);
        // 返回一个失败对象，但不调用 handleApiError 避免弹窗
        return { success: false, message: error.response?.data?.message || '答案自动保存失败' };
    }
};

/**
 * 提交考试
 * @param {number|string} id 考试ID
 * @param {object} submissionData 包含 answers 和监控数据的对象
 * @returns {Promise<object>} {success, message?, data?}
 */
export const submitExam = async (id, submissionData) => {
    try {
        const response = await axios.post(`${API_BASE_PATH}/${id}/submit`, submissionData);
        // 假设成功响应是 {success: true, message: "...", data: ...}
        return response.data; 
    } catch (error) {
        return handleApiError(error, '提交考试失败');
    }
};

/**
 * 获取当前学生进行中考试的剩余时间
 * @param {number|string} examId 考试ID
 * @returns {Promise<object>} {success, data?, message?} data 为剩余秒数
 */
export const getRemainingTime = async (examId) => {
    if (!examId) {
        console.warn('getRemainingTime: examId is required.');
        return { success: false, message: '缺少考试ID' };
    }
    try {
        const response = await axios.get(`${API_BASE_PATH}/${examId}/remaining-time`);
        // 假设成功响应是 {success: true, data: 3582}
        if (response.data && response.data.success && typeof response.data.data === 'number') {
            return { success: true, data: response.data.data };
        } else {
            // 如果后端直接返回数字，尝试兼容
            if (typeof response.data === 'number') {
                 console.warn(`API ${API_BASE_PATH}/${examId}/remaining-time returned a number directly. Wrapping it.`);
                 return { success: true, data: response.data };
            }
            const message = response.data?.message || '获取剩余时间失败或响应格式不正确';
            console.warn('getRemainingTime failed:', message, response.data);
            // 获取时间失败不弹窗提示，静默处理
            return { success: false, message, data: null };
        }
    } catch (error) {
        // 获取时间失败通常也静默处理，避免过多打扰
        console.error(`Error fetching remaining time for exam ${examId}:`, error.response?.data || error.message);
        return { success: false, message: error.response?.data?.message || '获取剩余时间请求失败', data: null };
    }
};

/**
 * 获取当前登录用户（学生或教师）的所有考试记录列表和统计信息
 * @returns {Promise<object>} {success, data?, message?} data 包含统计信息和记录列表
 */
export const getStudentExamRecordsList = async () => {
    try {
        const response = await axios.get(`${API_BASE_PATH}/my-records`);
        // 假设后端直接返回 {success, message, data: {stats..., examRecords: [...]}}
        return response.data;
    } catch (error) {
        return handleApiError(error, '获取考试记录列表失败');
    }
};

/**
 * 获取当前登录用户（学生或教师）在指定考试中的详细记录
 * @param {number|string} examId 考试ID
 * @returns {Promise<object>} {success, data?, message?} data 包含 examRecord, scoringDetails, examInfo
 */
export const getStudentExamRecordDetail = async (examId) => {
    if (!examId) {
        return { success: false, message: '必须提供考试ID' };
    }
    try {
        const response = await axios.get(`${API_BASE_PATH}/${examId}/my-record`);
         // 假设后端直接返回 {success, message, data: {examRecord, scoringDetails, examInfo}}
        return response.data;
    } catch (error) {
        return handleApiError(error, `获取考试 ${examId} 的记录详情失败`);
    }
};

/**
 * 教师获取指定学生的考试记录详情
 * @param {number|string} examId 考试ID
 * @param {number|string} studentId 学生ID
 * @returns {Promise<object>} {success, data?, message?} data 包含 examRecord, scoringDetails, examInfo
 */
export const getStudentRecordDetailForTeacher = async (examId, studentId) => {
    if (!examId || !studentId) {
        return { success: false, message: '必须提供考试ID和学生ID' };
    }
    try {
        // 注意 API 路径和查询参数 ?studentId=
        const response = await axios.get(`${API_BASE_PATH}/${examId}/student-record`, {
            params: { studentId }
        });
        // 假设后端直接返回 {success, message, data: {examRecord, scoringDetails, examInfo}}
        return response.data;
    } catch (error) {
        return handleApiError(error, `获取学生 ${studentId} 在考试 ${examId} 的记录详情失败`);
    }
};

// 新增统计接口：获取指定考试的统计信息
export const getExamStatistics = async (examId) => {
  if (!examId) {
    return { success: false, message: '必须提供考试ID' };
  }
  try {
    const response = await axios.get(`${API_BASE_PATH}/${examId}/statistics`);
    return response.data;
  } catch (error) {
    return handleApiError(error, `获取考试 ${examId} 统计信息失败`);
  }
}; 